package com.conv.shop.business.controller;

import cn.hutool.core.date.DateTime;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.conv.shop.business.config.AliPayConfig;
import com.conv.shop.business.domain.Address;
import com.conv.shop.business.domain.Order;
import com.conv.shop.business.domain.OrderExample;
import com.conv.shop.business.domain.Product;
import com.conv.shop.business.mapper.OrderMapper;
import com.conv.shop.business.mapper.ProductMapper;
import com.conv.shop.business.req.Alipay;
import com.conv.shop.business.service.AddressService;
import com.conv.shop.business.service.OrderService;
import com.conv.shop.business.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class PayController {
    //不加可能会导致进入付款界面乱码
    @Autowired
    private AliPayConfig aliPayConfig;
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    @Resource
    private OrderService orderService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private AddressService addressService;

    /**
     * 支付宝支付 api
     *
     //     * @param outTradeNo
     * @return
    //     * @throws AlipayApiException
     */

    int consumerId;
    @GetMapping("/pay")
    public void  pay(Alipay aliPay, HttpServletResponse httpResponse) throws Exception {
        Order order = orderService.getOrderByOrderNumber(aliPay.getOrderNumber());
        int productId = orderService.getProductId(aliPay.getOrderNumber());
        Product product = productMapper.selectByPrimaryKey(productId);
        String token = aliPay.getToken();
        consumerId = Integer.parseInt(JwtUtil.getUserNameByToken(token));
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//        String subject = aliPay.getTrainCode()+"--"+aliPay.getPassengerId();
        String subject = product.getProductName()+"("+order.getTotalAmount()+"元)";
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + order.getOrderNumber() + "\","
                + "\"total_amount\":\"" + order.getTotalAmount() + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(Alipay alipay, HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单未已支付
                Address address = addressService.getAddress(consumerId);
                String addressStr = address.getProvince()+address.getCity()+address.getDistrict()+address.getDetailedAddress();
                Date now = DateTime.now();
               Order order = new Order();
                order.setOrderStatus(1);
                order.setPaymentMethod("支付宝");
                order.setPaymentCompletedTime(now);
                order.setOrderNumber(tradeNo);
                order.setDeliveryAddress(addressStr);
                OrderExample orderExample = new OrderExample();
                orderExample.createCriteria().andOrderNumberEqualTo(tradeNo);
//                orderMapper.updateByPrimaryKeySelective(order);
                orderMapper.updateByExampleSelective(order,orderExample);
//                ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);
            }
        }
        return "success";
    }

}
